﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using EpiPoker.DataAccess;
using Facebook;

namespace EpiPoker.Account
{
    public partial class Login : System.Web.UI.Page
    {
        #region objects
        private AppFacebookService objFbService = new AppFacebookService();
        #endregion

        #region getters/setters
        public AppFacebookService ObjFbService
        {
            get { return objFbService; }
            set { objFbService = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            InitFbService();

            if (Session["facebook_userId"] != null)
                InitUser();

            FormsAuthentication.RedirectFromLoginPage(
                objFbService._fbService.GetUserInfo().FirstName + " " +
                objFbService._fbService.GetUserInfo().LastName,
                false);
            //Response.Redirect("../Default.aspx");
        }

        /// <summary>
        /// Initiate a new User with a Portfolio.
        /// </summary>
        /// <returns>Initiate a new User</returns>
        private void InitUser()
        {
            T_User user = null;

            try
            {
                user = DataAccess.User.GetUser(long.Parse(Session["facebook_userId"].ToString()));
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }

            if (user == null)
            {
                user = new T_User();

                try
                {
                    user.IdUser = long.Parse(Session["facebook_userId"].ToString());
                }
                catch (Exception Ex)
                {
                    Console.WriteLine(Ex.Message);
                }

                user.DateRegistration = DateTime.Now;
                user.IsActive = true;
                user.FirstName = objFbService._fbService.GetUserInfo().FirstName;
                user.LastName = objFbService._fbService.GetUserInfo().LastName;
                user.AvatarUrl = objFbService._fbService.GetUserInfo().PictureUrl.ToString();
                DataAccess.User.CreateUser(user);
                DataAccess.Portfolio.CreatePortfolio(user.IdUser, false);
            }
            else
            {
                user.FirstName = objFbService._fbService.GetUserInfo().FirstName;
                user.LastName = objFbService._fbService.GetUserInfo().LastName;
                user.AvatarUrl = objFbService._fbService.GetUserInfo().PictureUrl.ToString();
                DataAccess.User.UpdateUser(user);
            }
        }

        /// <summary>
        /// Initiate the Facebook service
        /// </summary>
        /// <returns>Initiate the facebook service</returns>
        private void InitFbService()
        {
            string sessionKey = Session["facebook_session_key"] as String;
            string userId = Session["facebook_userId"] as String;

            // When the user uses the facebook login page,
            // the redirect back here will have the auth_token in the query params
            string authToken = Request.QueryString["auth_token"];

            if (!String.IsNullOrEmpty(sessionKey))
            {
                objFbService._fbService.SessionKey = sessionKey;
                objFbService._fbService.UserId = userId;
            }
            else if (!String.IsNullOrEmpty(authToken))
            {
                objFbService._fbService.CreateSession(authToken);
                Session["facebook_session_key"] = objFbService._fbService.SessionKey;
                Session["facebook_userId"] = objFbService._fbService.UserId;
                Session["facebook_session_expires"] = objFbService._fbService.SessionExpires;
            }
            else
                Response.Redirect(@"http://www.facebook.com/login.php?api_key=" + objFbService._fbService.ApplicationKey + @"&v=1.0");

            Session["fbService"] = objFbService;
        }
    }
}
